const User = require('./user');
const Goods = require('./goods');
const Type = require('./type');
const Tag = require('./tag');
const UserAction = require('./user_action');
const GoodsTag = require('./goods_tag');
const History = require('./history');

// Goods 和 Type 的关联关系
Type.hasMany(Goods, {
  foreignKey: 'type',
  as: 'goodsList'
});

Goods.belongsTo(Type, {
  foreignKey: 'type',
  as: 'category'
});

// Goods 和 Tag 的多对多关联
Goods.belongsToMany(Tag, {
  through: GoodsTag,  // 通过中间表关联
  foreignKey: 'goods_id',  // 指向Goods的外键
  otherKey: 'tag_id',  // 指向Tag的外键
  as: 'tags'  // 关联别名
});

Tag.belongsToMany(Goods, {
  through: GoodsTag,
  foreignKey: 'tag_id',
  otherKey: 'goods_id',
  as: 'goodsList'
});

// 为中间表GoodsTag添加直接关联
GoodsTag.belongsTo(Tag, { 
  foreignKey: 'tag_id',
  as: 'tag'
});

GoodsTag.belongsTo(Goods, {
  foreignKey: 'goods_id',
  as: 'goods'
});

// User 和 UserAction 的关联关系
User.hasMany(UserAction, {
  foreignKey: 'user_id',
  as: 'actions'
});

UserAction.belongsTo(User, {
  foreignKey: 'user_id',
  as: 'user'
});

// Goods 和 UserAction 的关联关系
Goods.hasMany(UserAction, {
  foreignKey: 'goods_id',
  as: 'actions'
});

UserAction.belongsTo(Goods, {
  foreignKey: 'goods_id',
  as: 'goods'
});

// 设置Goods和History之间的一对一关联
Goods.belongsTo(History, { foreignKey: 'history_id', as: 'history' });
History.hasOne(Goods, { foreignKey: 'history_id' });

// 导出所有模型
module.exports = {
    User,
    Goods,
    Type,
    Tag,
    UserAction,
    GoodsTag,
    History
};